/*
 * @Author: mayijun
 * @Date: 2022-05-19 09:44:43
 * @LastEditors: mayijun
 * @LastEditTime: 2022-05-19 16:15:08
 */
//枚举值编辑
import {
  watchEffect,
  defineComponent,
  reactive,
  ref,
  computed,
  watch,
  onMounted
} from 'vue';
import { ElMessage } from 'element-plus/lib/index';
import './edit.scss';
import { RemoveFilled } from '@element-plus/icons-vue';
import API from '@/services';

const EnumEdit = defineComponent({
  name: 'EnumEdit',
  components: { RemoveFilled },
  props: {
    editInfo: {
      type: Object,
      default: () => {}
    },
    drawerVisible: {
      type: Boolean
    }
  },
  emits: ['refresh', 'update:drawerVisible'],
  setup: (props, { slots, attrs, emit }) => {
    const formRef: any = ref({});

    const form = reactive({
      cnName: '',
      description: '',
      addValue: [] as any,
      updateValue: [] as any,
      updateMapValue: {} as any,
      deleteValue: [] as any
    });

    const enumValueList: any = ref([]);

    const addInputShow = ref(false);

    const addEnumInput = ref();

    const enumId = ref();

    const drawerVisibles = computed({
      get: () => props.drawerVisible,
      set: (v) => emit('update:drawerVisible', v)
    });

    const rules = {
      cnName: [
        {
          required: true,
          message: '不能为空',
          trigger: ['blur', 'change']
        }
      ],
      description: [
        {
          required: true,
          message: '不能为空',
          trigger: ['blur', 'change']
        }
      ],
      enumName: [
        {
          required: true,
          message: '不能为空',
          trigger: ['blur']
        }
      ]
    };

    /* 添加输入枚举值 */
    const handlePushEnum = () => {
      const id: number = enumValueList.value.length + 1;
      enumValueList.value.unshift({ id, enumValue: addEnumInput.value });
      form.addValue.push(addEnumInput.value);
      addEnumInput.value = '';
      addInputShow.value = false;
    };

    const fetchRepeat = (person: any) => {
      const obj: any = {};
      const peon = person.reduce((cur: any, next: any) => {
        obj[next.id] ? '' : (obj[next.id] = true && cur.push(next));
        return cur;
      }, []);
      return peon;
    };

    /* 查询所有枚举值 */
    const queryConfigEnumById = async () => {
      try {
        const { code, data } =
          await API.dictionaryConfig.getDictionaryConfigById({
            id: enumId.value * 1
          });
        if (code === 200) {
          enumValueList.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    const confirmForm = async () => {
      formRef.value?.validate(async (valid: boolean) => {
        if (!valid) return;
        const res = fetchRepeat(form.updateValue);
        res?.forEach((v: any) => {
          form.updateMapValue[v.id] = v.enumValue;
        });
        const { code, data, msg } =
          await API.dictionaryConfig.putDictionaryConfigById(
            { id: enumId.value * 1 },
            {
              addValue: form.addValue,
              updateValue: form.updateMapValue,
              cnName: form.cnName,
              dictType: props?.editInfo.dictType,
              description: form.description,
              deleteValue: form.deleteValue
            }
          );

        if (code === 200) {
          ElMessage.success('编辑成功！');
          emit('refresh');
        } else {
          ElMessage.error(`编辑失败！${msg}`);
        }
      });
    };

    watchEffect(() => {
      const { editInfo } = props;
      form.cnName = editInfo?.cnName;
      form.description = editInfo?.description;
      enumId.value = editInfo?.id;
    });

    onMounted(() => {
      queryConfigEnumById();
    });

    return () => {
      const { editInfo } = props;
      return (
        <>
          <el-form
            class="system-ruleForm"
            rules={rules}
            model={form}
            ref={formRef}
            label-position={'right'}
            label-width="97px"
          >
            <el-form-item label="下拉项名称:" prop="cnName">
              <el-input
                size="large"
                style={{ width: '50%' }}
                v-model={form.cnName}
                placeholder="请填写"
              ></el-input>
            </el-form-item>

            <el-form-item label="英文名称:">
              <el-input
                size="large"
                style={{ width: '50%' }}
                disabled={true}
                v-model={editInfo.dictType}
                placeholder="请填写"
              ></el-input>
            </el-form-item>

            <el-form-item label="描述:" prop="description" size="medium">
              <el-input
                size="large"
                style={{ width: '50%' }}
                v-model={form.description}
                type="textarea"
              ></el-input>
            </el-form-item>

            <el-form-item label="下拉枚举值:" prop="enumValue" size="medium">
              <div class="enum-container">
                <div class="enum-container-item">
                  <div
                    class="addEnumBtn"
                    onClick={() => (addInputShow.value = true)}
                  >
                    +增加枚举值
                  </div>
                </div>
                {addInputShow.value && (
                  <div class="enum-container-btn">
                    <el-input
                      size="large"
                      onChange={() => handlePushEnum()}
                      v-model={addEnumInput.value}
                      placeholder="输入后回车"
                    />
                  </div>
                )}
                {enumValueList.value.map((v: any) => (
                  <div class="enum-container-item">
                    <el-input
                      size="large"
                      v-model={v.enumValue}
                      onChange={() => form.updateValue.push(v)}
                    />
                    <div
                      onClick={() => {
                        enumValueList.value = enumValueList.value.filter(
                          (item: any) => item.id !== v.id
                        );
                        form?.deleteValue.push(v.id);
                      }}
                      class="deleteIcon"
                    >
                      <el-icon color="#D2211B" size={16}>
                        <remove-filled />
                      </el-icon>
                    </div>
                  </div>
                ))}
              </div>
            </el-form-item>
          </el-form>
          <div class="footer-btn">
            <el-button onClick={() => (drawerVisibles.value = false)}>
              取消
            </el-button>
            <el-button type="primary" onClick={() => confirmForm()}>
              确定
            </el-button>
          </div>
        </>
      );
    };
  }
});
export default EnumEdit;
